package com.mjf.ue.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mjf.ue.config.U8Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/6/3 14:46
 */
@Component
public class UEHttpUtils {
    @Autowired
    private U8Config u8Config;
    /**
     * 发送GET请求
     *
     * @param apiPath
     * @param params
     * @return
     */
    public String sendGet(String apiPath, Map<String, Object> params) {
        params.put("app_key", u8Config.getApp_key());
        params.put("from_account", u8Config.getFrom_account());
        params.put("to_account", u8Config.getTo_account());
        params.put("ds_sequence", u8Config.getProd_ds_sequence());
        params.put("token", getToken());
        String url = u8Config.getUrl() + apiPath;
        // 发送GET请求
        String result = HttpUtil.createGet(url)
            .form(params) // 将参数加到请求中
            .execute()       // 执行请求
            .body();
        return result;
    }

    /**
     * 发送POST请求
     * @param apiPath
     * @param params
     * @return
     */
    public String sendPost(String apiPath, Map<String, Object> params) {
        String url = initPostUrlParam(apiPath, getToken(), getTradeId(), u8Config.getProd_ds_sequence());
        // 发送GET请求
        String result = HttpUtil.createPost(url)
            .header("Content-Type", "application/json")
            .body(JSON.toJSONString(params)) // 将参数加到请求中
            .execute()       // 执行请求
            .body();
        return result;
    }

    /**
     * 获取交易号
     * @return
     */
    public String getTradeId() {
        String token = TimedCacheUtils.get("u8_token");
        if (token == null) {
            throw new RuntimeException("获取token失败");
        }
        String trade = null;
        String url =
            u8Config.getUrl() + "/system/tradeid" + "?app_key=" + u8Config.getApp_key() + "&from_account=" + u8Config.getFrom_account() + "&token=" + token;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.getString("errcode"))) {
            trade = jsonObject.getJSONObject("trade").getString("id");
        }
        if (trade == null) {
            throw new RuntimeException("获取tradeid失败");
        }

        return trade;
    }
    /**
     * 获取token
     * @return
     */
    public String getToken() {
        String oldToken = TimedCacheUtils.get("u8_token");
        String token = "";
        if (oldToken == null) {
            String url =
                u8Config.getUrl() + "/system/token" + "?app_key=" + u8Config.getApp_key() + "&from_account=" + u8Config.getFrom_account() + "&app_secret=" + u8Config.getApp_secret();
            HttpRequest get = HttpUtil.createGet(url);
            HttpResponse execute = get.execute();
            String result = execute.body();
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("0".equals(jsonObject.getString("errcode"))) {
                token = jsonObject.getJSONObject("token").getString("id");
                Long expiresIn = jsonObject.getJSONObject("token").getLong("expiresIn");
                if (expiresIn == null) {
                    expiresIn = 7200L;
                }
//                else{
//                    expiresIn = expiresIn;
//                }
                TimedCacheUtils.put("u8_token", token, expiresIn);
            }
        } else {
            token = oldToken;
        }
        return token;
    }

    public String initPostUrlParam(String paramUrl, String token, String tradeId, String ds_sequence) {
        return u8Config.getUrl() + paramUrl + "?from_account=" + u8Config.getFrom_account() + "&to_account=" + u8Config.getTo_account() + "&app_key=" + u8Config.getApp_key() + "&token=" + token + "&tradeid=" + tradeId + "&sync=1" + "&ds_sequence=" + ds_sequence;
    }

    public String initGetUrlParam(String localUrl, String getUrlBody, String token) {
        return u8Config.getUrl() + localUrl + "?from_account=" + u8Config.getFrom_account() + "&to_account=" + u8Config.getTo_account() + "&app_key=" + u8Config.getApp_key() + "&token=" + token + "" + getUrlBody + "&ds_sequence=" + u8Config.getProd_ds_sequence();
    }

}
